package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;
    @Autowired
    IDepartmentService departmentService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"employee:view", "员工页面"}, logical = Logical.OR)
    public String view() {
        return "employee";
    }

    @RequestMapping("query")
    @ResponseBody
    @RequiresPermissions(value = {"employee:query", "员工列表"}, logical = Logical.OR)
    public PageResult query(EmployeeQueryObject qo) {
        return employeeService.query(qo);
    }

    @RequestMapping("getRoleIdByEmpId")
    @ResponseBody
    public List<Long> getRoleIdByEmpId(Long employeeId) {
        return employeeService.getRoleIdByEmpId(employeeId);
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"employee:saveOrUpdate", "员工新增/更改"}, logical = Logical.OR)
    public JsonResult saveOrUpdate(Employee emp) {
        try {
            if (emp.getId() != null) {
                employeeService.updateByPrimaryKey(emp);
            } else {
                //保存新的员工要设置默认的状态为在职
                emp.setState(true);
                employeeService.insert(emp);
            }
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("保存失败");
        }
    }

    @RequestMapping("changeState")
    @ResponseBody
    @RequiresPermissions(value = {"employee:changeState", "员工离职"}, logical = Logical.OR)
    public JsonResult changeState(Long id) {
        try {
            employeeService.changeState(id);
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("操作失败");
        }
    }

    @RequestMapping("changePassword")
    @ResponseBody
    public JsonResult changePassword(Long id) {
        try {
            employeeService.changePassword(id);
            int i = 1/0;
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("操作失败");
        }
    }

    @RequestMapping("validateUsername")
    @ResponseBody
    public boolean validateUsername(String username, Long id) {
        Employee employee = employeeService.getByUsername(username);
        //通过传回的用户名，如果查出来为null，则代表这个名字可以使用为true
        //如果查出来有值，且和传回的编辑的id相同，则相当于为同一个员工对象，允许保存，通过验证
        return employee == null || employee.getId() == id;
    }
    @RequestMapping("list")
    @ResponseBody
    public List<Employee> list() {
        return employeeService.selectlist();
    }

    @RequestMapping("exportXls")
    public void exportXls(HttpServletResponse response, EmployeeQueryObject qo) throws IOException {
        response.setHeader("Content-disposition", "attachment;filename=employee.xls");
        //创建excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建工作簿
        HSSFSheet sheet = workbook.createSheet("sheet01");
        //标题行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("入职时间");
        row.createCell(4).setCellValue("部门");
        row.createCell(5).setCellValue("电话");
        row.createCell(6).setCellValue("管理员");
        row.createCell(7).setCellValue("状态");
        List<Employee> list = employeeService.selectAll(qo);
        for (int i = 0; i < list.size(); i++) {
            Employee employee = list.get(i);
            row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getRealname());
            row.createCell(2).setCellValue(employee.getEmail());
            CreationHelper createHelper = workbook.getCreationHelper();
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setDataFormat(
                    createHelper.createDataFormat().getFormat("m/d/yy"));
            HSSFCell cellDate = row.createCell(3);
            cellDate.setCellStyle(cellStyle);
            cellDate.setCellValue(employee.getHireDate());
            row.createCell(4).setCellValue(employee.getDept().getName());
            row.createCell(5).setCellValue(employee.getTel());
            String admin = employee.getAdmin() ? "是" : "否";
            row.createCell(6).setCellValue(admin);
            String state = employee.getState() ? "在职" : "离职";
            row.createCell(7).setCellValue(state);
        }
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("importXls")
    public String importXls(MultipartFile file) throws IOException {
//读取excel文件(workbook)
        HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        //获取工作卜
        HSSFSheet sheet = workbook.getSheet("sheet01");
        //获取导入工作本的总行数
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i < lastRowNum; i++) {
            Employee employee = new Employee();
            //获取每一行数据
            HSSFRow row = sheet.getRow(i + 1);
            if (row != null && row.getCell(0) != null) {
                employee.setUsername(row.getCell(0).getStringCellValue());
                employee.setRealname(row.getCell(1).getStringCellValue());
                employee.setEmail(row.getCell(2).getStringCellValue());
                employee.setHireDate(row.getCell(3).getDateCellValue());
                String value = row.getCell(4).getStringCellValue();
                Long deptId = departmentService.selectByUserName(value);
                Department department = departmentService.selectByPrimaryKey(deptId);
                employee.setDept(department);
                employee.setTel(row.getCell(5).getStringCellValue());
                employee.setAdmin(row.getCell(6).getStringCellValue().equals("是"));
                employee.setState(row.getCell(7).getStringCellValue().equals("在职"));
                employee.setPassword("1");
                employeeService.insert(employee);
            }
        }
        workbook.close();
        return "temporary";
    }



    @RequestMapping("selectAll")
    @ResponseBody
    public List<Employee> selectAll() {
        return employeeService.selectAll();
    }




}
